package main

import (
	"blog_server/global"
	"blog_server/internal/router"
	_ "blog_server/setup"
	"context"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

//go:generate go mod tidy
//go:generate go mod download

// @title blog_server
// @version 1.0
// @description 基于gin的blog后端server
func main() {
	r := router.NewRouter()
	s := &http.Server{
		Addr:           ":" + global.ServerSetting.HttpPort,
		Handler:        r,
		ReadTimeout:    global.ServerSetting.ReadTimeout,
		WriteTimeout:   global.ServerSetting.WriteTimeout,
		MaxHeaderBytes: 1 << 20,
	}
	go func() {
		err := s.ListenAndServe()
		if err != nil && err != http.ErrServerClosed {
			global.Logger.Errorf("s.ListenAndServe err: %v", err)
			return
		}
	}()
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM,
		syscall.SIGQUIT)
	<-quit
	global.Logger.Infof("shuting down...")
	// 用于通知该服务有5秒时间处理原有的请求
	ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFunc()
	if err := s.Shutdown(ctx); err != nil {
		global.Logger.Fatalf("server forced to shutdown err: %v", err)
	}
	global.Logger.Infof("Server exited")
}
